/**
 * 
 */
package main.org.form.action;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import org.adempiere.exceptions.DBException;
import org.apache.struts2.interceptor.SessionAware;
import org.compiere.model.I_AD_Ref_List;
import org.compiere.model.MBPMForm;
import org.compiere.model.MRefList;
import org.compiere.model.MTable;
import org.compiere.model.MUser;
import org.compiere.model.PO;
import org.compiere.model.Query;
import org.compiere.model.X_AD_Ref_List;
import org.compiere.model.X_BPM_BudgetCall;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.ValueNamePair;

import com.opensymphony.xwork2.ActionContext;

import main.org.model.Budget;
import main.org.model.Utils;

/**
 * @author V.Sokolov
 * 
 */
public class Forms extends Budget implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8168009313401256223L;

	public static final String sessionKey = "forms";
	protected String page;
	protected int AD_Client_ID;
	protected int AD_Org_ID;
	protected int BPM_VersionBudget_ID;
	protected int BPM_Project_ID;
	protected int AD_User_ID;
	protected MBPMForm[] formsLine;
	protected String DocStatus;
	protected boolean ReadOnly;
    
    /* 
	 */
	@Override
	public String execute() throws Exception {
//		HttpSession session = ServletActionContext.getRequest().getSession(true);
//		System.out.println("Session_ID : " +session.getId()); 
		
		//m.put("sessid",session.getId()); 
		
		setPage(Utils.TEMPLATE_FIRST);
		StringBuilder err = new StringBuilder();
				
		Env.setContext(Env.getCtx(), "#AD_Client_ID", AD_Client_ID);
		Env.setContext(Env.getCtx(), "#AD_Org_ID", AD_Org_ID);
		Env.setContext(Env.getCtx(), "#AD_Language", getLang());
		Env.setContext(Env.getCtx(), "#AD_User_ID", AD_User_ID);
		Env.setContext(Env.getCtx(), "#BPM_VersionBudget_ID", BPM_VersionBudget_ID);
		Env.setContext(Env.getCtx(), "#BPM_Project_ID", BPM_Project_ID);

		
		formsLine = MBPMForm.getForms(BPM_VersionBudget_ID,AD_Org_ID);

		if (formsLine.length == 0)
			err.append("Нет форм с настройками на данный бюджетный календарь <br />");

		if (BPM_VersionBudget_ID == 0)
			err.append("Не найден текущий бюджетный календарь на год <br />");

		if (BPM_Project_ID == 0)
			err.append("Не найден рабочий проект <br />");

		if (AD_Org_ID < 0) {
			err.append("Неверно настроен справочник Орг. единиц <br />");
			if (AD_User_ID == 0)
				err.append("Не найден ID пользователя или головная организация<br />");
		}
		this.setMessageError(err.toString());
		
		if (err.length() == 0) {
			int BPM_Project_Agreement_ID=0;
			String sql = "SELECT BPM_Project_Agreement_ID FROM BPM_Project_Agreement " 
						+"\n WHERE BPM_Project_ID = "+BPM_Project_ID
						+"\n AND AD_Client_ID = "+AD_Client_ID
						+"\n AND AD_Org_ID = "+AD_Org_ID;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			try {
				pstmt = DB.prepareStatement(sql, null);
				rs = pstmt.executeQuery();
				while (rs.next()) {
					BPM_Project_Agreement_ID = rs.getInt(1);
				}
			} catch (SQLException e) {
				CLogger.get().log(Level.INFO, sql, e);
				throw new DBException(e, sql);
			} finally {
				DB.close(rs, pstmt);
				rs = null;
				pstmt = null;
			}
	        MTable table = MTable.get(Env.getCtx(), "BPM_Project_Agreement");
	        PO po = table.getPO (BPM_Project_Agreement_ID, null);
			if (BPM_Project_Agreement_ID==0) {
				po.set_ValueOfColumn("AD_Org_ID",AD_Org_ID);
				po.set_ValueOfColumn("BPM_Project_ID", BPM_Project_ID);
				po.set_ValueOfColumn("Description","Согласование бюджетных форм. "+new MUser(Env.getCtx(),AD_User_ID,null).getDescription());
				po.set_ValueOfColumn("AGR_Dispatcher_ID",1000003);
				po.saveEx();
			} 
			this.DocStatus = po.get_ValueAsString("DocStatus");
			if (X_BPM_BudgetCall.DOCSTATUS_Approved.equals(DocStatus)||
					X_BPM_BudgetCall.DOCSTATUS_OnApproval.equals(DocStatus))
				this.ReadOnly=true;
			else this.ReadOnly=false;
			if (AD_Org_ID==0) this.ReadOnly=true;
			this.session.put(Forms.sessionKey, this);
			return SUCCESS;
		} else
			return NONE;

	}

	/*
	 */
	@Override
	public String input() throws Exception {
		this.session = ActionContext.getContext().getSession();
		StringBuilder err = new StringBuilder();
		setMessageError(err.toString());
		if (err.length() != 0)
				return NONE;

		return INPUT;
	}
	
	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public void setAD_Client_ID(int AD_Client_ID) {
		this.AD_Client_ID = AD_Client_ID;
	}

	public int getAD_Client_ID() {
		return AD_Client_ID;
	}
	
	public int getAD_Org_ID() {
		return AD_Org_ID;
	}

	public void setAD_Org_ID(int AD_Org_ID) {
		this.AD_Org_ID = AD_Org_ID;
	}

	public int getBPM_VersionBudget_ID() {
		return BPM_VersionBudget_ID;
	}

	public void setBPM_VersionBudget_ID(int BPM_VersionBudget_ID) {
		this.BPM_VersionBudget_ID = BPM_VersionBudget_ID;
	}

	public void setBPM_Project_ID(int BPM_Project_ID) {
		this.BPM_Project_ID = BPM_Project_ID;
	}

	public int getBPM_Project_ID() {
		return BPM_Project_ID;
	}	

	public void setAD_User_ID(int AD_User_ID) {
		this.AD_User_ID = AD_User_ID;
	}

	public int getAD_User_ID() {
		return AD_User_ID;
	}	

	public MBPMForm[] getFormsLine() {
		return  formsLine; 
	}	

	public MBPMForm[] getFormsLine(String CategoryName) {
		List<MBPMForm> filteredFormsLines = new ArrayList<MBPMForm>();
		for(MBPMForm filteredFormsLine: formsLine)
		{
			if(filteredFormsLine.get_Value("BPM_FormOrderBy").equals(CategoryName))
				filteredFormsLines.add(filteredFormsLine);
		}
		return  filteredFormsLines.toArray(new MBPMForm[filteredFormsLines.size()]); 
	}
	
	public String getDocStatus() {
		return  MRefList.getListName(Env.getCtx(), 1000149, DocStatus); 
	}	

    public boolean getReadOnly() {
        return ReadOnly;
    } 
}
